package com.dkm.modules.sys.operator.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dkm.commons.BaseController;
import com.dkm.commons.PageQueryParams;
import com.dkm.commons.Response;
import com.dkm.constant.Constant;
import com.dkm.exception.ServiceException;
import com.dkm.modules.sys.operator.model.OperatorResult;
import com.dkm.modules.sys.operator.model.OperatorSelect;
import com.dkm.modules.sys.operator.model.SetOperatorDTO;
import com.dkm.modules.sys.operator.model.UserOperator;
import com.dkm.modules.sys.operator.service.OperatorService;
import com.dkm.modules.sys.user.mapper.UserMapper;
import com.dkm.modules.sys.user.model.AddUser;
import com.dkm.modules.sys.user.model.EditUser;
import com.dkm.modules.sys.user.model.User;
import com.dkm.modules.wx.cashrecord.service.OperatorCashRecordService;
import com.dkm.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @ClassName OperatorController
 * @Description: 代理商管理
 * @Author 杨膑
 * @Date 2019/9/4
 * @Version V1.0
 **/
@Api(tags = "A8 代理商管理")
@RestController
@RequestMapping("/operator")
public class OperatorController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(OperatorController.class);

    @Autowired
    private OperatorService operatorService;

    @Autowired
    private OperatorCashRecordService operatorCashRecordService;
    @Autowired
    private UserMapper userMapper;


    @ApiOperation("给运营者配置代理商")
    @PostMapping("/setOperatorsForUser")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response setOperatorsForUser(@Valid @RequestBody SetOperatorDTO setOperatorDTO) {
        operatorService.setOperatorsForUser(setOperatorDTO);
        return Response.ok();
    }

    @ApiOperation("删除运营者的某个代理商权限")
    @PostMapping("/deleteOpertaors")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response deleteOpertaors(@RequestParam("id") @ApiParam(value = "关联关系id") Integer id) {
        if(Objects.isNull(id)){
            throw new ServiceException("关联关系id不能为空");
        }
        operatorService.deleteOpertaors(id);
        return Response.ok();
    }

    @ApiOperation("获取所有生效的运营者")
    @GetMapping("/allUser")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response allUser() {
        List<User> users = operatorService.getAllUser();
        return Response.ok(users);
    }

    @ApiOperation("运营者权限分页查询")
    @GetMapping("/getUserOperators")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response<IPage<UserOperator>> getUserOperatorsByPage(@ApiParam("搜索关键字") @RequestParam(value = "keyWord", required = false) String keyWord,
                                                                PageQueryParams p) {

        IPage<UserOperator> users = operatorService.getUserOperatorsByPage(keyWord, new Page<>(p.getPageNo(), p.getPageSize()));
        return Response.ok(users);
    }

    @ApiOperation("添加代理商")
    @PostMapping("/add")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response add(@ApiParam("代理商数据") @RequestBody AddUser operator) {
        logger.info("添加代理商");
        return operatorService.addUser(operator);
    }


    @ApiOperation("获取代理商列表")
    @GetMapping("/getOperatorList")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response<IPage<OperatorResult>> getOperatorList(@ApiParam("搜索关键字") @RequestParam(value = "keyWord", required = false) String keyWord,
                                                           PageQueryParams p) {

        logger.info("获取代理商列表");
        Page<OperatorResult> page = new Page<>(p.getPageNo(), p.getPageSize());

        //*组装查询参数*//*
        Map<String, String> params = new HashMap<>();
        //搜索关键字
        params.put("keyWord", getPara("keyWord"));
        //获取端口分页后列表
        IPage<OperatorResult> operatorList = operatorService.getOperatorList(page, params);
        return Response.ok(operatorList);
    }

    @ApiOperation("删除代理商")
    @DeleteMapping("delOperator")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response delOperator(@ApiParam @RequestParam("id") Integer id) {
        logger.info("删除代理商:" + id);
        operatorService.delOperator(id);
        return Response.ok();
    }

    @ApiOperation("修改代理商")
    @PostMapping("editOperator")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response editOperator(@ApiParam("代理商数据") @RequestBody EditUser user) {
        logger.info("修改代理商");
        User userByMobile = userMapper.getAgentByMobile(user.getMobile());
        if (userByMobile != null && !StringUtils.equals(userByMobile.getUserName(), user.getUserName())) {
            return Response.error(-1, "手机号已存在，请换一个手机号！");
        }
        if (!StringUtils.isPhoneNumber(user.getMobile())) {
            return Response.error(-1, "手机号不正确.");
        }
        operatorService.editOperator(user);
        return Response.ok();
    }

    @ApiOperation("代理商select框")
    @GetMapping("getOperatorSelect")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response<List<OperatorSelect>> getOperatorSelect() {
        logger.info("获取代理商select ");
        List<OperatorSelect> operatorSelects = operatorService.getOperatorSelect();
        return Response.ok(operatorSelects);
    }

    @ApiOperation("提现记录")
    @GetMapping("/getCashRecord")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response getCashRecord(@ApiParam("页数") @RequestParam("pageNo") int pageNo,
                                  @ApiParam("每页显示数") @RequestParam("pageSize") int pageSize, @ApiParam("代理商id") @RequestParam("operatorId") int operatorId) {

        Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);
        /*组装查询参数*/
        Map<String, Object> params = new HashMap<>(8);
        /*代理商*/
        params.put("userId", operatorId);
        /*查询分页提现记录*/
        IPage<Map<String, Object>> cashRecords = operatorCashRecordService.getCashRecords(page, params);
        return Response.ok(cashRecords);
    }


    @ApiOperation("获取累计分成金额")
    @GetMapping("/getAccumulatedAmount")
    @ApiImplicitParam(paramType = "header",name = "token",value = "身份认证Token")
    public Response getAccumulatedAmount(@ApiParam("代理商id") @RequestParam("operatorId")int operatorId){
        return operatorService.getAccumulatedAmount(operatorId);
    }

    @ApiOperation("设置代理商分成比例")
    @GetMapping("/setUpRoyaltyPercent")
    @ApiImplicitParam(paramType = "header",name = "token",value = "身份认证Token")
    public Response setUpRoyaltyPercent(@ApiParam("代理商id") @RequestParam("operatorId")int operatorId,@ApiParam("代理商分成比例，在0.01到99.99之间") @RequestParam("royaltyPercent") BigDecimal royaltyPercent){
        if(royaltyPercent.compareTo(new BigDecimal("0.01")) < 0 || royaltyPercent.compareTo(new BigDecimal("99.99"))>0){
            return  Response.error(Constant.SUCCESS_CODE,-2,"代理商分成比例，在0.01到99.99之间",null);
        }
        royaltyPercent = royaltyPercent.setScale(2, RoundingMode.HALF_UP);
        return operatorService.setUpRoyaltyPercent(operatorId,royaltyPercent);
    }



}
